/**
 * Person.java
 * 
 * This class represents a person.
 *
 * @author Felix Schuller
 */

package Runde2;


import java.util.ArrayList;

public abstract class Person {
	private ArrayList<Message> inbox;
	private String fName;
	private String lName;
	private String password;
	
	/**
	 * Creates a new person.
	 * 
	 * @param matrNr - matriculation number
	 * @param fName - first name
	 * @param lName - last name
	 * @param password - password
	 * @throws InvalidPersonException - thrown if fName/lName/password is a empty string
	 */
	public Person(String fName, String lName, String password) throws InvalidPersonException {
		if (fName.equals("") || lName.equals("") || password.equals("")) {
			throw new InvalidPersonException("Emtpy first name, lastname or password given");
		}
		this.fName = fName;
		this.lName = lName;
		this.password = password;
		inbox = new ArrayList<Message>();
	}
	
	/**
	 * @return - returns student's full name
	 */
	public String getName() {
		return fName + " " + lName;
	}
	
	/**
	 * Puts given message into person's inbox.
	 * 
	 * @param m - message to send
	 */
	public void sendMessage(Message m){
		inbox.add(m);
	}
	
	/**
	 * Returns all unread messages.
	 * 
	 * @param password - password
 	 * @throws InvalidPermissionsException - thrown if wrong password was given
 	 * @return unread messages
	 */
	public String getNewMessages(String password) throws InsufficientPermissionsException {
		if (!validate(password)){
			throw new InsufficientPermissionsException("Permission denied.");
		}
		
		String output = "";
		for (Message m : inbox) {
			if (!m.wasRead()) {
				output += m + "\n";
			}
		}
		
		if (output.equals("")) {
			return "Keine neuen Nachrichten.\n";
		}
		
		return output;
	}
	
	/**
	 * Returns message with given index from inbox
	 * 
	 * @param index - message's index
	 * @param password - password
 	 * @throws InvalidPermissionsException - thrown if wrong password was given
 	 * @return message with given index
	 */
	public String getMessage(int index, String password) throws InsufficientPermissionsException {
		if (!validate(password)){
			throw new InsufficientPermissionsException("Permission denied.");
		}
		return inbox.get(index).toString();
	}
	
	/**
	 * Returns true or false whether the given password was "correct" or not
	 * 
	 * @param password - given password
	 * @return true/false whether the given password was "correct" or not
	 */
	public boolean validate(String password) {
		if (this.password.equals(password)) {
			return true;
		}
		return false;
	}
	
	/**
	 * Returns readable form of person
	 * 
	 * @return person's full name
	 */
	public String toString(){
		return fName + " " + lName;
	}
}
